package com.etone.android.test.utils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;

import org.xmlpull.v1.XmlSerializer;

import android.util.Log;
import android.util.Xml;

import com.etone.android.test.constants.AndroidTestConstants;
import com.etone.android.test.constants.LogType;

/**
 * xml日志类
 * 
 * @author LiuWeiJie
 * @date 2012-1-6
 */
public class Log2XmlUtils {
	private String logFile;
	private XmlSerializer serializer;
	private StringWriter writer;
	private Long beginTime;

	public Log2XmlUtils(String logFile) {
		this.logFile = logFile;
		this.beginTime = System.currentTimeMillis();

		create();
	}

	/**
	 * 新建xml文件
	 */
	private void create() {
		serializer = Xml.newSerializer();
		writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", AndroidTestConstants.XML_ROOT_TAG);
			serializer.attribute("", "date", DateUtils.getCurrentDateString());
		} catch (Exception e) {
			Log.e(AndroidTestConstants.LOG_TAG, e.getMessage());
		}
	}

	/**
	 * 添加日志节点
	 * 
	 * @param logType
	 * @param todo
	 * @param msg
	 */
	public void addNode(LogType logType, String todo, String msg) {
		try {
			serializer.startTag("", AndroidTestConstants.XML_LOG_TAG);
			serializer.attribute("", "type", LogType.toString(logType));
			serializer.attribute("", "time",
					(System.currentTimeMillis() - beginTime) + "");
			serializer.attribute("", "todo", todo);
			serializer.attribute("", "msg", msg);
			serializer.endTag("", AndroidTestConstants.XML_LOG_TAG);
		} catch (Exception e) {
			Log.e(AndroidTestConstants.LOG_TAG, e.getMessage());
		}
	}

	
	 /**
	  * 保存xml文件
	  */
	public void save() {
		try {
			serializer.endTag("", AndroidTestConstants.XML_ROOT_TAG);
			serializer.endDocument();
			OutputStream os = new FileOutputStream(logFile);
			OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
			osw.write(writer.toString());
			osw.flush();
			osw.close();
			os.close();
		} catch (Exception e) {
			Log.e(AndroidTestConstants.LOG_TAG, e.getMessage());
		}
	}
}
